﻿using System;
using System.Windows;

namespace StartTool
{
    public partial class MainWindow : Window
    {
        private System.Windows.Forms.NotifyIcon _notifyIcon;
        private WindowState wsl; //记录窗口状态
        private bool _CanClose = false; //能否关闭，用来控制用户点击关闭按钮后触发的关闭事件

        public MainWindow()
        {
            InitializeComponent();

            _notifyIcon = new System.Windows.Forms.NotifyIcon();
            _notifyIcon.Visible = false;
            _notifyIcon.BalloonTipText = "锁屏关闭微信";
            _notifyIcon.ShowBalloonTip(2000);
            _notifyIcon.Text = "锁屏关闭微信";
            _notifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath);

            //打开菜单项
            System.Windows.Forms.MenuItem open = new System.Windows.Forms.MenuItem("打开");
            open.Click += new EventHandler(ShowWindow);
            //退出菜单项
            System.Windows.Forms.MenuItem exit = new System.Windows.Forms.MenuItem("关闭");
            exit.Click += (o, e) => { btnExit_Click(o, null); };
            //关联托盘控件
            System.Windows.Forms.MenuItem[] childen = new System.Windows.Forms.MenuItem[] { open, exit };
            _notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(childen);

            _notifyIcon.MouseClick += new System.Windows.Forms.MouseEventHandler((o, e) =>
            {
                if (e.Button == System.Windows.Forms.MouseButtons.Left) ShowWindow(o, e);
            });

            wsl = WindowState;
        }

        public void ShowWindow(object sender, EventArgs e)
        {
            if (Visibility == Visibility.Visible)
            {
                Activate();
                Topmost = true;
                Topmost = false;
            }
            else
            {
                Show();
                WindowState = wsl;
                ShowInTaskbar = true;
                _notifyIcon.Visible = false;
            }
        }

        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            _CanClose = true;
            Close();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (!_CanClose)
            {
                e.Cancel = true;
                WindowState = WindowState.Minimized;
                return;
            }

            if (_notifyIcon != null)
                _notifyIcon.Dispose();
            _notifyIcon = null;
        }
        private void Window_StateChanged(object sender, EventArgs e)
        {
            if (WindowState == WindowState.Minimized)
            {
                Hide();
                _notifyIcon.Visible = true;
            }
            else
                wsl = WindowState;
        }

    }
}
